# code 为js代码
# template 为html代码


# 创建一个form类
class Form:
    need_init_functions = []

    def __init__(self, form):
        self.form = form

    def generate_form_item(self, field):
        # form_item 类型包含 text, select, radio, checkbox, date, textarea，el-upload
        if field['type'] == 'text':
            return f'''<el-form-item label="{field['label']}" prop="{field['name']}">
                    <el-input v-model="ruleForm.{field['name']}"></el-input>
                </el-form-item>'''

        elif field['type'] == 'select':
            return f'''<el-form-item label="{field['label']}" prop="{field['name']}">
                    <el-select v-model="ruleForm.{field['name']}">
                        <el-option v-for="item in {field['options']}" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>'''

        elif field['type'] == 'radio':
            return f'''<el-form-item label="{field['label']}" prop="{field['name']}">
                    <el-radio-group v-model="ruleForm.{field['name']}">
                        <el-radio v-for="item in {field['options']}" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>'''

        elif field['type'] == 'checkbox':
            return f'''<el-form-item label="{field['label']}" prop="{field['name']}">
                    <el-checkbox-group v-model="ruleForm.{field['name']}">
                        <el-checkbox v-for="item in {field['options']}" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>'''

        elif field['type'] == 'date':
            return f'''<el-form-item label="{field['label']}" prop="{field['name']}">
                    <el-date-picker v-model="ruleForm.{field['name']}" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>'''

        elif field['type'] == 'textarea':
            return f'''<el-form-item label="{field['label']}" prop="{field['name']}">
                    <el-input type="textarea" v-model="ruleForm.{field['name']}"></el-input>
                </el-form-item>'''

    # 生成表单模板
    def generate_form_template(self):
        form = self.form

        tpl = ''
        for field in form['fields']:
            tpl += self.generate_form_item(field)

        return tpl

    def generate_import_code(self):
        form = self.form
        need_import_type = ['select', 'radio', 'checkbox']
        imports = ''
        for field in form['fields']:

            if field['type'] in need_import_type and 'api' in field:
                # 将apiFunction添加到need_init_functions
                self.need_init_functions.append(field['apiFunction'])
                imports += f'''
        import {{ {field['apiFunction']} }} from '@/api/{field['api']}'
        const {field['options']} = ref([])
        // 从接口获取数据
        {field['apiFunction']}().then(res => {{
            {field['options']}.value = res.data
        }})
        '''
        return imports

    def generate_form_code(self):
        form = self.form
        rule_form = 'const ruleForm = ref({'
        rules = 'const rules = ref({'

        for form in form['fields']:

            if form['type'] == 'text':
                rule_form += f'''{form['name']}: '','''
                rules += f'''{form['name']}: [{{ required: true, message: '请输入{form['label']}', trigger: 'blur' }}],'''

            if form['type'] == 'select':
                rule_form += f'''{form['name']}: '','''
                rules += f'''{form['name']}: [{{ required: true, message: '请选择{form['label']}', trigger: 'change' }}],'''

            if form['type'] == 'radio':
                rule_form += f'''{form['name']}: '','''
                rules += f'''{form['name']}: [{{ required: true, message: '请选择{form['label']}', trigger: 'change' }}],'''

            if form['type'] == 'checkbox':
                rule_form += f'''{form['name']}: [],'''
                rules += f'''{form['name']}: [{{ required: true, message: '请选择{form['label']}', trigger: 'change' }}],'''

            if form['type'] == 'date':
                rule_form += f'''{form['name']}: '','''
                rules += f'''{form['name']}: [{{ required: true, message: '请选择{form['label']}', trigger: 'change' }}],'''

            if form['type'] == 'textarea':
                rule_form += f'''{form['name']}: '','''
                rules += f'''{form['name']}: [{{ required: true, message: '请输入{form['label']}', trigger: 'blur' }}],'''

        rule_form += '});\n'
        rules += '});'

        return rule_form + rules

    def generate_submit_code(self):
        form = self.form
        submit = f'''import {{ {form['apiFunction']} }} from '{form['api']}';
        const ruleFormRef = ref(null);
        const onSubmit = () => {{
            ruleForm.value.validate((valid) => {{
                if (valid) {{
                    {form['apiFunction']}(ruleForm.value).then(res => {{
                        if (res.code === 200) {{
                            ElMessage.success(res.msg);
                            ruleFormRef.value.resetFields();
                            emits('reload');
                        }} else {{
                            ElMessage.error(res.msg);
                        }}
                    }})
                }}
            }})
        }}'''
        return submit